<template>
  <div class="chat-container">
    <div class="chat-messages" ref="messageBox">
      <div v-for="(msg, index) in messages" :key="index" :class="['message-item', msg.role]">
        <div class="avatar">
          <el-avatar :size="40" :src="msg.role === 'user' ? userAvatar : botAvatar" />
        </div>
        <div class="bubble">
          <p>{{ msg.text }}</p>
        </div>
      </div>
    </div>

    <div class="chat-input">
      <el-input v-model="inputText" type="textarea" placeholder="メッセージを入力..." :rows="2" @keyup.enter="handleSend" />
      <el-button type="primary" :disabled="!inputText.trim() || !isConnected" @click="handleSend">
        送信
      </el-button>
    </div>

    <div class="status-bar">
      <el-tag :type="isConnected ? 'success' : 'danger'">
        {{ isConnected ? "🟢 接続中" : "🔴 切断" }}
      </el-tag>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, nextTick } from "vue";
import { Client } from "@stomp/stompjs";
import SockJS from "sockjs-client";
import { useRoute } from "vue-router"; // ✅ 引入 useRoute
import { getToken } from '@/utils/auth'

const route = useRoute(); // ✅ 获取路由对象

// ✅ 获取传入的好友 ID
const targetUserId = ref(route.query.id || null);
const targetUserNickname = ref(route.query.nickname || '未知用户');
const currentUserId = localStorage.getItem('userId');
// const targetUserId = ref(route.params.id || null);
// const targetUserNickname = ref(route.params.nickname || '未知用户');
// const targetUserAvatar = ref(route.params.avatar || 'https://i.pravatar.cc/40?img=1');

// 原有代码...
const inputText = ref("");
const messages = ref([]);
const messageBox = ref(null);
const stompClient = ref(null);
const isConnected = ref(false);
const userAvatar = "https://i.pravatar.cc/40?img=12";
const botAvatar = "https://i.pravatar.cc/40?img=8";

// 滚动到底部
const scrollToBottom = async () => {
  await nextTick();
  const el = messageBox.value;
  if (el) el.scrollTop = el.scrollHeight;
};

// 修改连接逻辑：使用 targetUserId 作为订阅地址的一部分
const connectWebSocket = () => {
  stompClient.value = new Client({
    webSocketFactory: () => new SockJS(`/ws?userId=${currentUserId}`),
    connectHeaders: { 'Authorization': "Bearer " + getToken() },
    debug: (str) => console.log("STOMP: " + str),
    reconnectDelay: 3000,
    heartbeatIncoming: 4000,
    heartbeatOutgoing: 4000,

    onConnect: () => {
      isConnected.value = true;
      messages.value.push({
        role: "bot",
        text: `✅ 与 ${targetUserNickname.value} 的连接已建立`
      });
      scrollToBottom();

      // ✅ 订阅：每个用户订阅 /user/queue/messages
      stompClient.value.subscribe('/user/queue/messages', (message) => {
        try {
          const data = JSON.parse(message.body);
          console.log("数据", data.content)
          if (data.fromUserId === currentUserId) return;
          const role = String(data.fromUserId) === String(currentUserId) ? 'user' : 'other';
          messages.value.push({
            role,
            text: data.content || data.text
          });
        } catch (e) {
          console.log("进入异常了")
          messages.value.push({ role: "bot", text: message.body });
        }
        scrollToBottom();
      });
    },

    onStompError: (frame) => {
      console.error("STOMP error:", frame);
      isConnected.value = false;
      messages.value.push({ role: "bot", text: "⚠️ 接続エラーが発生しました。" });
      scrollToBottom();
    },

    onWebSocketClose: () => {
      isConnected.value = false;
      messages.value.push({ role: "bot", text: "⚠️ 接続が切断されました。再接続を試みます..." });
      scrollToBottom();
    }
  });

  stompClient.value.activate();
};

// 发送消息时，带上目标用户 ID
const handleSend = () => {
  const text = inputText.value.trim();
  if (!text || !isConnected.value) return;

  messages.value.push({ role: "user", text });

  // ✅ 发送消息时，包含目标用户 ID
  stompClient.value.publish({
    destination: "/app/chat.send", // 后端会根据消息内容路由
    body: JSON.stringify({
      content: text,
      role: "user",
      toUserId: targetUserId.value, // ✅ 发送给谁 
      fromUserId: localStorage.getItem('userId') // 可选：当前用户
    })
  });

  inputText.value = "";
  scrollToBottom();
};

onMounted(connectWebSocket);
onBeforeUnmount(() => {
  if (stompClient.value) {
    stompClient.value.deactivate();
  }
});
</script>
<!-- <script setup>
import { ref, onMounted, onBeforeUnmount, nextTick } from "vue";
import { Client } from "@stomp/stompjs";
import SockJS from "sockjs-client";
import { useRoute } from "vue-router"; // ✅ 引入 useRoute
// ✅ 获取传入的好友 ID
const targetUserId = ref(route.params.id || null);
const targetUserNickname = ref(route.params.nickname || '未知用户');
const targetUserAvatar = ref(route.params.avatar || 'https://i.pravatar.cc/40?img=1');
const inputText = ref("");
const messages = ref([]);
const messageBox = ref(null);
const stompClient = ref(null);
const isConnected = ref(false);
const userAvatar = "https://i.pravatar.cc/40?img=12";
const botAvatar = "https://i.pravatar.cc/40?img=8";

const scrollToBottom = async () => {
  await nextTick();
  const el = messageBox.value;
  if (el) el.scrollTop = el.scrollHeight;
};

const connectWebSocket = () => {
  // Create STOMP client with SockJS
  stompClient.value = new Client({
    webSocketFactory: () => new SockJS("/ws"),

    // Connection headers (添加需要的头部信息)
    connectionTimeout: 5000,

    // Reconnection settings
    reconnectDelay: 3000,
    heartbeatIncoming: 4000,
    heartbeatOutgoing: 4000,

    // Debug output (optional, can be disabled in production)
    debug: (str) => {
      console.log("STOMP: " + str);
    },

    // On successful connection
    onConnect: () => {
      isConnected.value = true;
      messages.value.push({
        role: "bot",
        text: "✅ サーバーに接続しました。"
      });
      scrollToBottom();

      // Subscribe to receive messages from server
      stompClient.value.subscribe("/user/queue/messages", (message) => {
        try {
          const data = JSON.parse(message.body);
          messages.value.push({
            role: data.role || "bot",
            text: data.text
          });
        } catch {
          messages.value.push({ role: "bot", text: message.body });
        }
        scrollToBottom();
      });
    },

    // On connection error
    onStompError: (frame) => {
      console.error("STOMP error:", frame);
      isConnected.value = false;
      messages.value.push({
        role: "bot",
        text: "⚠️ 接続エラーが発生しました。"
      });
      scrollToBottom();
    },

    // On WebSocket close
    onWebSocketClose: () => {
      isConnected.value = false;
      messages.value.push({
        role: "bot",
        text: "⚠️ 接続が切断されました。再接続を試みます..."
      });
      scrollToBottom();
    }
  });

  // Activate the STOMP client
  stompClient.value.activate();
};

const handleSend = () => {
  const text = inputText.value.trim();
  if (!text || !isConnected.value) return;

  messages.value.push({ role: "user", text });

  // Send message via STOMP
  stompClient.value.publish({
    destination: "/app/chat.send",
    body: JSON.stringify({ text, role: "user" })
  });

  inputText.value = "";
  scrollToBottom();
};

onMounted(connectWebSocket);
onBeforeUnmount(() => {
  if (stompClient.value) {
    stompClient.value.deactivate();
  }
});
</script> -->

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 90vh;
  max-width: 800px;
  margin: 30px auto;
  border: 1px solid #e5e5e5;
  border-radius: 12px;
  background: #fff;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  background: #f8f9fa;
}

.message-item {
  display: flex;
  margin-bottom: 14px;
  align-items: flex-start;
}

.message-item.user {
  flex-direction: row-reverse;
}

.bubble {
  max-width: 70%;
  padding: 10px 14px;
  border-radius: 12px;
  background: white;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  word-break: break-word;
}

.message-item.user .bubble {
  background: #0078d7;
  color: white;
}

.avatar {
  margin: 0 10px;
}

.chat-input {
  display: flex;
  gap: 8px;
  padding: 12px;
  border-top: 1px solid #eee;
  background: #fff;
}

.status-bar {
  text-align: right;
  padding: 6px 12px;
  border-top: 1px solid #eee;
  font-size: 13px;
}
</style>
